<?php

namespace App\Http\Controllers\SystemManagement;

use App\Http\Controllers\Controller;
use App\Models\Constant\Fields;
use App\Models\SystemManagement\User;
use App\Models\SystemManagement\UserRole;
use Illuminate\Http\Request;
use App\Http\Requests\System\User as UserRequest;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

/**
 * Class UserController
 * @package App\Http\Controllers\SystemManagement
 * @group 用户（指定用户设置密码）
 */
class UserController extends Controller
{
    /**
     * 用户列表
     *
     * @return \Illuminate\Http\Response
     *
     * @queryParam id int required 用户ID
     * @queryParam username string required 登录账户
     * @queryParam password string required 登录密码
     * @queryParam employee_id int required 员工ID
     * @queryParam start_time datetime required 有效期-启用时间
     * @queryParam end_time datetime required 有效期-结束时间
     * @queryParam status int required 启用
     * @queryParam picture int required 头像id
     * @queryParam condition string required 个人签名;状态
     * @queryParam file->local_url string 头像url地址
     *
     */
    public function index()
    {
        $page = \request()->input('per_page');
        $data = User::orderBy(Fields::ID,'desc')->with(['employees','userRole','file'])->paginate($page);
        return response()->json(encodeMsg($data,200));
    }

    /**
     * 新增用户
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     *
     * @bodyParam username string required 登录账户
     * @bodyParam password string required 登录密码
     * @bodyParam employee_id int required 员工ID
     * @bodyParam start_time datetime required 有效期-启用时间
     * @bodyParam end_time datetime required 有效期-结束时间
     * @bodyParam status int required 启用
     * @bodyParam picture int required 头像id
     * @bodyParam condition string required 个人签名;状态
     *
     * @response 201 {"msg":"添加成功"}
     * @response 400 {"msg":"参数错误/添加失败"}
     */
    public function store(UserRequest $request)
    {
        $req = $request->input();
        if(count($req) == 0){
            return response()->json(encodeMsg("参数错误",400));
        }
        DB::beginTransaction();
        try{
            $req['password'] = Hash::make($req['password']);
            $user = User::create($req);
            if($request->has('role_id')){
                $data['user_id'] = $user->id;
                $data['role_id'] = $request->input('role_id','');
                UserRole::create($data);
            }
            DB::commit();
            return response()->json(encodeMsg("添加成功",201));
        }catch (\Exception $e){
            DB::rollBack();
            dd($e->getMessage());
            return response()->json(encodeMsg("添加失败",400));
        }

    }

    /**
     * 查看用户
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     *
     * @bodyParam id int required 用户id
     *
     * @queryParam id int required 用户ID
     * @queryParam username string required 登录账户
     * @queryParam password string required 登录密码
     * @queryParam employee_id int required 员工ID
     * @queryParam start_time datetime required 有效期-启用时间
     * @queryParam end_time datetime required 有效期-结束时间
     * @queryParam status int required 启用
     * @queryParam picture int required 头像id
     * @queryParam condition string required 个人签名;状态
     * @queryParam file->local_url string 头像url地址
     *
     * @response 200 {"msg":"success","code":200,"data":{"id":6,"username":"admin","remember_token":null,"user_id":null}}
     * @response 404 {"msg":"api not found","code":404,"data":"\u7ba1\u7406\u5458\u4e0d\u5b58\u5728"}
     */
    public function show($id)
    {
        $data = User::where('id',$id)->with(['employees','userRole','file'])->first();
        if(is_null($data)){
            return response()->json(encodeMsg('用户不存在',404));
        }
        return response()->json(encodeMsg($data,200));
    }

    /**
     * 修改用户
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     *
     * @bodyParam id int required 用户ID
     * @bodyParam username string required 登录账户
     * @bodyParam password string required 登录密码
     * @bodyParam employee_id int required 员工ID
     * @bodyParam start_time datetime required 有效期-启用时间
     * @bodyParam end_time datetime required 有效期-结束时间
     * @bodyParam status int required 启用
     * @bodyParam picture int required 头像id
     * @bodyParam condition string required 个人签名;状态
     *
     * @response 205 {"msg":"修改成功"}
     * @response 400 {"msg":"参数错误/修改失败/原密码不正确"}
     * @response 404 {"msg":"该用户不存在"}
     */
    public function update(UserRequest $request, $id)
    {
        $user = User::where('id',$id)->with('userRole')->first()->toArray();
        if(is_null($user)){
            return response()->json(encodeMsg("该用户不存在",404));
        }
        $req = $request->input();
        if($req == []){
            return response()->json(encodeMsg("参数错误",400));
        }
        $req['password'] = Hash::make($req['password']);
        DB::beginTransaction();
        try{
            User::find($id)->update($req);
            $role_id = $request->input('role_id','');
            if(isset($user['user_role'])){
                if($user['user_role'][0]['role_id'] != $role_id){
                    UserRole::where('user_id',$id)->delete();
                    $data['user_id'] = $id;
                    $data['role_id'] = $role_id;
                    UserRole::create($data);
                }
            }
            DB::commit();
            return response()->json(encodeMsg("修改成功",205));
        }catch (\Exception $e){
            DB::rollBack();
            dd($e->getMessage());
            return response()->json(encodeMsg("修改失败",400));
        }

    }

    /**
     * 修改个性签名;状态
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     *
     * @bodyParam id int required 用户ID
     * @bodyParam picture int optional 头像id
     * @bodyParam condition string optional 个人签名;状态
     *
     * @response 205 {"msg":"修改成功"}
     */
    public function updateCondition(Request $request, $id)
    {
        $user = User::find($id);
        if(is_null($user)){
            return response()->json(encodeMsg("该用户不存在",404));
        }
        $req = $request->input();
        if($req == []){
            return response()->json(encodeMsg("参数错误",400));
        }
        try{
            $user->update($req);
            return response()->json(encodeMsg("修改成功",205));
        }catch (\Exception $e){
            dd($e->getMessage());
            return response()->json(encodeMsg("修改失败",400));
        }
    }

    /**
     * 修改密码
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     *
     * @bodyParam id int required 用户ID
     * @bodyParam username string required 登录账户
     * @bodyParam old_password string required 旧密码
     * @bodyParam new_password string required 新密码
     * @bodyParam employee_id int required 员工ID
     * @bodyParam start_time datetime required 有效期-启用时间
     * @bodyParam end_time datetime required 有效期-结束时间
     * @bodyParam status int required 启用
     * @bodyParam picture int required 头像id
     * @bodyParam condition string required 个人签名;状态
     *
     * @response 205 {"msg":"修改成功"}
     * @response 400 {"msg":"参数错误/修改失败/原密码不正确"}
     * @response 404 {"msg":"该用户不存在"}
     */
    public function updatePwd(UserRequest $request, $id)
    {
        $user = User::find($id);
        if(is_null($user)){
            return response()->json(encodeMsg("该用户不存在",404));
        }
        if (!Hash::check($request->input('old_password'),$user->password)){
            return response()->json(encodeMsg("原密码不正确",400));
        }
        $req = $request->input();
        if($req == []){
            return response()->json(encodeMsg("参数错误",400));
        }
        $req['password'] = Hash::make($req['new_password']);
        unset($req['old_password']);
        unset($req['new_password']);
        try{
            $user->update($req);
            return response()->json(encodeMsg("修改成功",205));
        }catch (\Exception $e){
            dd($e->getMessage());
            return response()->json(encodeMsg("修改失败",400));
        }

    }

    /**
     * 单条删除用户
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     *
     * @bodyParam id int 用户id
     *
     * @response 204 {"msg":"deleted","code":204,"data":"删除成功"}
     * @response 400 {"msg":"param error","code":400,"data":"删除失败"}
     * @response 404 {"msg":"not found","code":404,"data":"用户不存在"}
     */
    public function destroy($id)
    {
        $user = User::find($id);
        if(is_null($user)){
            return response()->json(["status"=>404,"message"=>"用户不存在"]);
        }
        DB::beginTransaction();
        try{
            $user->delete();
            UserRole::where(Fields::USER_ID,$id)->delete();
            DB::commit();
            return response()->json(encodeMsg("删除成功",205));
        }catch (\Exception $e){
            dd($e->getMessage());
            DB::rollBack();
            return response()->json(encodeMsg("删除失败",400));
        }
    }

    /**
     * 删除用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam ids array required id数组
     *
     * @response 204 {code":204,"msg":"deleted","data":"成功"}
     * @response 400 {"code":400,"msg":"parameter error","data":"失败"}
     */
    public function del(Request $request)
    {
        $ids = $request->input('ids');
        foreach ($ids as $k=>$id){
            $ids[$k] = (int) $id;
        }
        try{
            User::whereIn(Fields::ID,$ids)->delete();
            UserRole::whereIn(Fields::USER_ID,$ids)->delete();
            return response()->json(encodeMsg("删除成功",204));
        }catch (\Exception $e){
            //dd($e->getMessage());
            return response()->json(encodeMsg("删除失败",400));
        }
    }

    /**
     * 查看用户拥有角色
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam id int required the Manager of the id.
     *
     * @queryParam id 用户ID
     * @queryParam account 用户账号
     * @queryParam name 用户姓名
     * @queryParam type 用户类型
     * @queryParam contact 联系对象
     * @queryParam department_id 所属部门ID
     * @queryParam phone 联系电话
     * @queryParam description 用户说明
     * @queryParam Manager_role 用户拥有的角色{"id":1,"Manager_id":1,"role_id":"1,2,3"}
     *
     * @response 200 {"msg": "success","code": 200,"data": {"id": 1,"account": "111111","name": "张三","type": "员工","contact": "1","department_id": 1,"phone": "13333333333","description": "请问请问","Manager_role": [{"id": 1,"Manager_id": 1,"role_id": "1,2,3"}]}}
     * @response 404 {"msg":"api not found","code":404,"data":"该用户不存在"}
     */
    public function getUserHasRole($id){
        $data = User::with('UserRole')->find($id);
        if(is_null($data)){
            return response()->json(encodeMsg("该用户不存在",404));
        }
        return response()->json(encodeMsg($data,200));
    }


}
